package com.guardchina.framework.util.gson;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 描述：日期时间序列化
 *
 * @author lwb
 * @date 2019/3/21 11:29
 */
public class LocalDateTimeSerializer implements JsonSerializer<LocalDateTime>, JsonDeserializer<LocalDateTime> {
    private String dateTimePattern;

    public LocalDateTimeSerializer(String pattern){
        this.dateTimePattern = pattern;
    }

    @Override
    public JsonElement serialize(LocalDateTime src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(src.format(DateTimeFormatter.ofPattern(dateTimePattern)));
    }

    @Override
    public LocalDateTime deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        String dateTime = jsonElement.getAsJsonPrimitive().getAsString();
        return LocalDateTime.parse(dateTime, DateTimeFormatter.ofPattern(dateTimePattern));
    }
}
